var fundTypeMap={};//基金代码和描述映射
//科室指标监测页签变量
var depquota = [{
	code : 'depGroupMonitor',
	name : '科室未达标指标监测',
	data : [{
			name : "科室未达标指标监测",
			data : [{
			        	"quotaCode" : "TargetLastYear",
						"quotaName" : "与年初管理相比",
						'quotaDetil':'科室年初管理目标'
					},{ 
					     "quotaCode":"Benchmark",
					     "quotaName":"与标杆管理相比",
					     'quotaDetil':'科室当前病组病例数与病组标杆(全市均值)求和平均'
			    	 },{
			    		 "quotaCode":"TargetThisYear",
					     "quotaName":"与实际管理相比",
					     'quotaDetil':'科室当前病组病例数与病组目标(科室DRG目标)求和平均'
			    	 }
		    	 ]
			}]
}];
var routineQuota = {"AvgFee":"次均费用（元）","TotalCaseCnt":"出院人数","AvgDays":"平均住院日","DrugRatio":"药占比(%)","MaterialRatio":"耗占比(%)"};
var drgQuota = {"FeeEff":"费用消耗指数","TotalWeight":"总权重","TimeEff":"时间消耗指数"};
$(function(){
        // 字典映射值获取
		var fundType = diction.FUND_TYPE;
		if (typeof(fundType) != "undefined") {
			for (var m = 0; m < fundType.length; m++) {
				fundTypeMap[fundType[m].DICVALUE] = fundType[m].DICDESC;
			}
			// 加载医保总基金信息
			loadHCInfo();
		} else {
			drgUI.error("请先去系统配置模块配置基金类型");
			return;
		}

	//第二部分时间轴加载布局和数据
	loadTimeEchartsDiv(routineQuota,drgQuota);//加载指标监测页面结构
    loadTimeEcharts(paramTabPage[tabId].hospCode);//加载时间轴
	loadVennDiv(depquota,"depquotamonitordiv","depquotamonitorul");//加载venn图页面结构
	drawDepQuotaVenn(paramTabPage[tabId].hospCode);//绘制科室指标监测venn图
	$('#toShow').click(function(){
		if($('#depquotamonitordiv .tab-content .active .showDetil').css('display') == 'none'){
			$('#depquotamonitordiv .tab-content .active .showDetil').fadeIn(1000);
		}else{
			$('#depquotamonitordiv .tab-content .active .showDetil').fadeOut(1000);
		}
		
	});
});
/**
 * 
 * @ Discription:拼接基金类型
 * @Autor ：liuhongjun
 * @returns
 * any
 * yibaoHomePage.js
 * 2017年6月20日下午4:52:15
 */
function loadHCInfo(){
	//获取医保基金类型数据
	$.post(contextPath+"/systemConfig/getConfigByCode.dhc",{alterParam: "MED_INS_TYPE"}).done(function(result){
		var medInsData = result.data;// 基金类型数据
		if(medInsData && medInsData.length>0){
			var medInsArr  =medInsArr = medInsData.split("θ")==null?[]:medInsData.split("θ");// 基金类型数组
			var insType = {};// 基金类型数组
			var insTypeStr="";
			for(var i=0;i<medInsArr.length;i++){
				insType[medInsArr[i].split("#")[0]]=medInsArr[i].split("#")[1];
				insTypeStr+="<option value="+medInsArr[i].split("#")[0]+">"+fundTypeMap[medInsArr[i].split("#")[0]]+"</option>";
			}
			$("#"+tabId+" #instype").html(insTypeStr);
			loadHC($("#"+tabId+" #instype").val(),$("#"+tabId+" #instype").text());
			$("#"+tabId+" #instype").on("change",function(){
				loadHC($("#"+tabId+" #instype").val(),$("#"+tabId+" #instype").text());
			});
		}else{
				$("#"+tabId+" #totalFund_content").html("<div style='width: 100px;text-align: center; margin: auto;color: red;'>未配置基金类型</div>")
				drgUI.warning("请先去系统配置模块配置基金类型");
		}
	});
}
/**
 * 
 * @ Discription:获取医保基金数据
 * @Autor ：liuhongjun
 * @param o 基金代码
 * @returns
 * any
 * yibaoHomePage.js
 * 2017年6月20日上午7:55:52
 */
function loadHC(o,funTypeDesc){
	var hospCode=paramTabPage[tabId].hospCode;
	$.post(contextPath + "/yibaohome/getHCInfoHosp.dhc", {hiType: o,hospCode:hospCode}).done(function(result){
		if(result.success && result.data){
			var monthval = 0;
			var data=result.data;
			if(result.data){
				var datam = data.data;
				var year = data.year;
				if(datam){
					if(datam[3]["thisYear"]>0 && datam[4]["thisYear"]>0){
						monthval = (datam[4]["thisYear"]/datam[3]["thisYear"]*100).toFixed(0);
					}
					var monthdata = {value: monthval, name: ''};
					var yearval = 0;
					if(datam[1]["thisYear"]>0 && datam[2]["thisYear"]>0){
						yearval = (datam[2]["thisYear"]/datam[1]["thisYear"]*100).toFixed(0);
					}
					var yeardata = {value: yearval, name: ''};
					drawDashBoardChart("monthfundChart",monthdata,"月度使用率");
					drawDashBoardChart("fundChart",yeardata,"年度使用率");
					drawDashBoardTable("fundTable",datam,year,o,funTypeDesc,hospCode);
				}else{
					drawDashBoardChart("monthfundChart",0,"月度使用率");
					drawDashBoardChart("fundChart",0,"年度使用率");
					drawDashBoardTable("fundTable",null,year,o,funTypeDesc,hospCode);
				}
			}
		
		}
	});	
}

/**
 * 
 * @ Discription:医保基金表格
 * @Autor ：liuhongjun
 * @param id
 * @param data
 * @param year
 * @param o
 * @returns
 * any
 * yibaoHomePage.js
 * 2017年6月20日上午7:56:35
 */
function drawDashBoardTable(id,data,year,o,funTypeDesc,hospCode){
	var lastYear = '';
	if(year == null){
		year = '无数据';
		lastYear = '无数据';
	}else{
		lastYear=year-1;
	}
		$("#"+tabId+" #"+id).html('<table id="'+id+'datatable'+'" class="table table-striped" style="width:100%;"></table>');
		var thistitle='今年('+year+')';
		var lasttitle='去年('+lastYear+')';
		var columns=[
					 	  {   "title":"",
					 		  "data":"ybName"
					 	  },
	                      {    
					 		 "title":thistitle,
					 		 "data":"thisYearo",	                    	
					 		 "render": function(obj, type, full) {
	                    		if(full.thisYear==null){
	                    			return "";
	                    		}else{
	                    			return formatNumber(full.thisYear);
	                    		}
	                         }
                 	 },
	                     { 
                 		    "title":lasttitle,
                 		    "data":"lastYearo",
	                    	"render": function(obj, type, full) {
	                    		if(full.lastYear==null){
	                    			return "";
	                    		}else{
	                    			return formatNumber(full.lastYear);
	                    		}
	                         }
                 	 },
	                     { 
                 		   "title":"同比增长",
                 		   "data":"grow",
	                    	"render": function(obj, type, full) {
	                             return gridcompareValue(full.thisYear, full.lastYear);
	                         }
                 	 },
                 	 { 
                 		"title":"操作",
                 		 "data": "operation","className":"textCenter",
                 		 "render": function(obj, type, full,meta){
                 			 if(meta.row==2){
                 				 return "<a title='历史使用情况' href=\"javascript:loadHCHistory('"+o+"','"+year+"','"+hospCode+"')\">历史</a>&nbsp;&nbsp;"
                 				 }
            			 }
                 	 }
	                 ];
		var paramsDataTables={paging:false,searching:false,lengthChange:false,info:false,tableTitle:funTypeDesc+'-医保基金情况表',ordering:false,rownumbers:true,columnDefs:[{"orderable": false,"targets": [ 0 ] },{ "visible": true, "targets": [0]}]};
		$("#"+tabId+" #"+id+'datatable').dataTableBasic(columns,data,paramsDataTables);
}

//加载医保类型分布
function loadHCDistribute(type){

	 $.post(contextPath + '/pages/common/top-dialog.jsp').done(function(data){
			var dialog  = $(data);
			dialog.find(".modal-title").html("正在开发中...");
			dialog.modal({
				keyboard: false
			}).on({
				'hidden.bs.modal' : function(){
					$(this).remove();
				},
				'shown.bs.modal' : function(){}
			});
	 });
	

}

/**
 * 
 * @ Discription:查询历史数据
 * @Autor ：liuhongjun
 * @param o
 * @returns
 * any
 * yibaoHomePage.js
 * 2017年6月28日下午8:04:29
 */
function loadHCHistory(o,year,hospCode){
	 $.post(contextPath + '/pages/common/top-dialog.jsp').done(function(data){
			var dialog  = $(data);
			dialog.find(".modal-title").html(year+"年每月医保费用使用情况");
			dialog.modal({
				keyboard: false
			}).on({
				'hidden.bs.modal' : function(){
					$(this).remove();
				},
				'shown.bs.modal' : function(){
					$.post(contextPath + "/yibaohome/getHCHistory.dhc", {hiType: o,hospCode: hospCode}).done(function(result){
						var data=result.data;
						var total = new Array();
						var left = new Array();
						var over = new Array();
						var monthData = new Array();
						var echartData=[];
						for(var i=0;i<data.length;i++){
							
							if(data[i][3]>0){
								over[i] = data[i][3];
								left[i] = 0;
								total[i] = data[i][1]-data[i][3];//实际值是data[i][1]，但是画堆叠图，要减去超出部分
								monthData[i] = data[i][4];
							} else if(data[i][3]<0){
								over[i] = 0;
								left[i] = -data[i][3];
								total[i]=data[i][1];//实际值是data[i][1]
								monthData[i] = data[i][4];
							} else {
								total[i] = 0;
								over[i] = 0;
								monthData[i] = data[i][4];
							}
							echartData[i]={ddesc:monthData[i],actual:total[i],surplus:left[i],over:over[i]};
						}
						var itemStyle={"normal": {barBorderColor:'#50a1d4',barBorderWidth :2},"emphasis":{barBorderColor:'#58B1E9',barBorderWidth :2}};
						var surplusItemStyle={"normal": {barBorderColor:'#7bd9a5',barBorderWidth :2},"emphasis":{barBorderColor:'#87EEB5',barBorderWidth :2}};
						var overItemStyle={"normal": {barBorderColor:'#50a1d4',barBorderWidth :2},"emphasis":{barBorderColor:'#58B1E9',barBorderWidth :2}};
						var barColor=["#50a1d4","#7bd9a5","#f07043"];
						var lines = [{"code":'actual',"desc": '实际', "data":[],itemStyle:itemStyle}, {"code":'surplus',"desc":'结余', "data":[],itemStyle:surplusItemStyle}, {"code":'over',"desc":'超出', "data":[],itemStyle:overItemStyle}];
						var formatterFunc=function(value){
							var tips='';
							if(value!=undefined && value.length>0){
								//说明value 0:当超出时，为拨款值 结余时为实际值; 1：结余值;  2：超出值
								//实际值
								if(value[2].value>0){
									tips+=value[0].seriesName+":"+(value[0].value+value[2].value)+ '</br>';
								}
								else{
									tips+=value[0].seriesName+":"+value[0].value+ '</br>';
								}
								//结余
								if(value[1].value>0){
									tips+=value[1].seriesName+":"+value[1].value+ '</br>';
								}
								else{
									tips+=value[1].seriesName+":"+0+ '</br>';
								}
								//超出
								if(value[2].value>0){
									tips+=value[2].seriesName+":"+value[2].value+ '</br>';
								}
								else{
									tips+=value[2].seriesName+":"+0+ '</br>';
								}
								//拨款值
								if(value[2].value>0){
									tips+="拨款:"+value[0].value.toFixed(2)+ '</br>';
								}
								else{
									tips+="拨款:"+(value[0].value+value[1].value).toFixed(2)+ '</br>';//实际+结余
								}
					    	   
				    	   }
							return tips;
						};
						var chartParams={isStack:true,legendPosition:'top',barColor:barColor,formatterFunc:formatterFunc};
						barChart(dialog.find(".echartscq"), lines, echartData, year+"年每月医保费用使用情况(单位：万元)", '',chartParams)
						});
				}
			});
	 });
	
}
//医保总基金仪表盘图
function drawDashBoardChart(id,data,title){
	var chartParams={};
	gaugeCharts($("#"+tabId+" #"+id),data,title,"使用率",'',chartParams);
}

/**
 * 
 * @ Discription:加载时间轴分布div
 * @Autor ：liuhongjun
 * @param routineQuota
 * @param drgQuota
 * @returns
 * any
 * yibaoHomePage.js
 * 2017年6月30日下午4:59:49
 */
function loadTimeEchartsDiv(routineQuota,drgQuota){
	
	var str = '';
	var ul = '';
	var i = 0;
	str += '<div role="tabpanel" class="tab-pane active">';
	str += '	<div class="paddingd10"> ';
	str += '		<ul class="nav nav-tabs tabconulcq" role="tablist"> ';
	for (var key in routineQuota) {
		if (i == 0) {
			str += '	<li role="presentation" class="active"> ';
		} 
		else {
			str += '	<li role="presentation"> ';
		}
		str += '			<a href="#' + key + '-tc' + tabId + '" role="tab" quotaCodeTime="'+key+'" data-toggle="tab">' + routineQuota[key] + '</a> ';
		str += '       </li> ';
		i = i+1;
	}
	str += '		</ul> ';
	str += '	</div>';
	str += '</div>';
	str += '	<div class="clearfix"></div> ';
	str += '	<div class="tab-content"> ';
	i=0;
	for (var key in routineQuota) {
		if (i == 0) {
			str += '       <div role="tabpanel" class="tab-pane active" id="'+ key+ '-tc'+ tabId+ '"> ';
		} 
		else {
			str += '       <div role="tabpanel" class="tab-pane" id="'+ key+ '-tc'+ tabId+ '"> ';
		}
		str += '           <div class="row padding100"> ';
		str += '               <div class="col-xs-12"><div id  = "venncharts'+key+tabId+'" style=""> ';
		str += ' ';
		str += '               </div></div> ';
		str += '           </div> ';
		str += '       </div> ';
		i=i+1;
	}
	str += '	</div>';
	$("#" + tabId + " #yibao_routineQuotaDiv").html(str);
	str = '';
	ul = '';
	i = 0;
	str += '<div role="tabpanel" class="tab-pane active">';
	str += '	<div class="paddingd10"> ';
	str += '		<ul class="nav nav-tabs tabconulcq" role="tablist"> ';
	for (var key in drgQuota) {
		if (i == 0) {
			str += '	<li role="presentation" class="active"> ';
		} else {
			str += '	<li role="presentation"> ';
		}
		str += '			<a href="#' + key + '-drgtc' + tabId + '" quotaCodeTime="'+key+'" role="tab" data-toggle="tab">' + drgQuota[key] + '</a> ';
		str += '       </li> ';
		i = i+1;
	}
	str += '		</ul> ';
	str += '	</div>';
	str += '</div>';
	str += '	<div class="clearfix"></div> ';
	str += '	<div class="tab-content"> ';
	i=0;
	for (var key in drgQuota) {
		if (i == 0) {
			str += '       <div role="tabpanel" class="tab-pane active" id="'+ key+ '-drgtc'+ tabId+ '"> ';
		} else {
			str += '       <div role="tabpanel" class="tab-pane" id="'+ key+ '-drgtc'+ tabId+ '"> ';
		}
		str += '           <div class="row padding100"> ';
		str += '                <div class="col-xs-12"><div id  = "vennchartsdrg'+key+tabId+'" style=""> ';
		str += ' ';
		str += '               </div></div> ';
		str += '           </div> ';
		str += '       </div> ';
		i=i+1;
	}
	str += '	</div>';
	$("#" + tabId + " #yibao_drgQuotaDiv").html(str);
}
/**
 * 
 * @ Discription:加载时间轴数据
 * @Autor ：liuhongjun
 * @returns
 * any
 * yibaoHomePage.js
 * 2017年6月21日上午8:02:05
 */
function loadTimeEcharts(hospCode){
	$('#'+tabId+' #yibao_routineQuotaDiv').find('a').each(function(m,obj){
		var qoutaCode=$(obj).attr('quotaCodeTime');
		if(m==0){
			getData(qoutaCode, "",hospCode);
	    }	
		$(obj).click(function(){
				getData(qoutaCode, "",hospCode);
				//点击之后将点击事件销毁
				$(obj).unbind( "click" );
		})
	});
	
	$('#'+tabId+' #yibao_drgQuotaDiv').find('a').each(function(n,obj){
		var qoutaCode=$(obj).attr('quotaCodeTime');
		if(n==0){
			getData(qoutaCode, "drg",hospCode);
	    }	
		$(obj).click(function(){
			getData(qoutaCode, "drg",hospCode);
			//点击之后将点击事件销毁
			$(obj).unbind( "click" );
		})
	});
}
/**
 * 
 * @ Discription:获取各指标数据
 * @Autor ：liuhongjun
 * @param key
 * @param t
 * @returns
 * any
 * yibaoHomePage.js
 * 2017年6月21日上午7:59:02
 */
function getData(key, t,hospCode){
	drgUI.bindAjaxStart(0);
	echartLoadingInit($("#venncharts"+ t+key +tabId));
	$.post(contextPath + "/yibaohome/findHospQuotaData.dhc", {
		 "quotaCode": key,
		 "hospCode":hospCode
	 }).done(function(result){
		drawTimeChart(result.data, t+key);
		drgUI.bindAjaxStart(1);
	});
}

//画时间轴图
function drawTimeChart(data, key){
	var quotaDesc={AvgFee:'次均费用',TotalCaseCnt:'出院人数',AvgDays:'平均住院日',DrugRatio:'药占比',MaterialRatio:'耗占比',drgFeeEff:'费用消耗指数',drgTotalWeight:'总权重',drgTimeEff:'时间消耗指数'};
	var data1 = [];
	var data2 = [];
	var echartData=[];
	if(data.all && data.all.length >0){
		for(var n=0;n<data.all.length;n++)
		{
			data1.push({ddesc:data.all[n].ddesc,all:data.all[n]["QuotaValue"]});
			data2.push({ddesc:data.all[n].ddesc,medins:data.mendis[n]["QuotaValue"]});
		}
		echartData=[data1,data2];
	}
	var unit = '';
	if (key.toLowerCase().indexOf('ratio')>-1) {
		unit = '%';
	}
	
	var lines = [{"code":'all',"desc": '全部病人', "data":[]},{"code":'medins',"desc":'医保病人', "data":[]}];
	var fommaterFunc=function (params,ticket,callback) {
        var res =  params[0].name;
        for (var i = 0, l = params.length; i < l; i++) {
            res += '<br/>' + params[i].seriesName + ' : ' + formatNumber(params[i].value) + unit;
        }
        return res;
    }
	if(!$("#searchcq").children().eq(3).find("div.ci a").eq(0).hasClass("active"))
 	{
		fommaterFunc=0;//不设置提示框
 	}
	var chartParams={titleShow:false,fommaterFunc:fommaterFunc,legendPosition:'top',isDataZoom:true,unit:unit,autoWidth:true,autoHeight:'auto',heightRatio:0.6};
	lineChartBasic($("#venncharts"+ key +tabId),lines,echartData,quotaDesc[key]+'趋势图','',chartParams);
}

/**
 * 绘制科室指标的venn图 科室指标监测请求数据（第三部分）
 */
function drawDepQuotaVenn(hospCode) {
	$.post(contextPath + "/yibaohome/depQuotaMonitor.dhc",{"hospCode":hospCode}).done(function(result){
		var tableData = [];
		//年初管理值
		var seriesTL = [ {
			name : '次均费用',
			data : []
		}, {
			name : '平均住院日',
			data : []
		}, {
			name : '药占比',
			data : []
		} ];
		//实际管理值
		var seriesTT = [ {
			name : '次均费用',
			data : []
		}, {
			name : '平均住院日',
			data : []
		}, {
			name : '药占比',
			data : []
		} ];
		//标杆管理值
		var seriesB = [ {
			name : '次均费用',
			data : []
		}, {
			name : '平均住院日',
			data : []
		}, {
			name : '药占比',
			data : []
		} ]; 
		var data = result.data;
		var l = data==undefined?0:data.benchmark.length;
		//构造表格数据
		for(var i = 0; i<l; i++){
			var tmpArr = {};
			tmpArr.code=data.targetT[i][0];//科室代码
			tmpArr.name=data.targetT[i][7];//科室名称
			tmpArr.avgfee=data.targetT[i][1]==null?0:data.targetT[i][1];//次均费用
			tmpArr.avgday=data.targetT[i][2]==null?0:data.targetT[i][2];//平均住院日
			tmpArr.drugratio=data.targetT[i][3]==null?0:data.targetT[i][3];//药占比
			tmpArr.feeTL=data.targetL[i][4]==null?0:data.targetL[i][4];//次均费用-年初管理值
			tmpArr.dayTL=data.targetL[i][5]==null?0:data.targetL[i][5];//平均住院日-年初管理值
			tmpArr.drugTL=data.targetL[i][6]==null?0:data.targetL[i][6];//药占比-年初管理值
			tmpArr.feeB=data.benchmark[i][4]==null?0:data.benchmark[i][4];//次均费用-标杆管理值
			tmpArr.dayB=data.benchmark[i][5]==null?0:data.benchmark[i][5];//平均住院日-标杆管理值
			tmpArr.drugB=data.benchmark[i][6]==null?0:data.benchmark[i][6];//药占比-标杆管理值
			tmpArr.feeTT=data.targetT[i][4]==null?0:data.targetT[i][4];//次均费用-实际管理值
			tmpArr.dayTT=data.targetT[i][5]==null?0:data.targetT[i][5];//平均住院日-实际管理值
			tmpArr.drugTT=data.targetT[i][6]==null?0:data.targetT[i][6];//药占比-实际管理值
			var feeb_TT = false;//实际管理值 bool变量
			var feeb_B = false;//标杆管理值 bool变量
			//年初管理值
			if(tmpArr.avgfee>tmpArr.feeTL){//当前科室次均费用超标
				seriesTL[0].data.push(tmpArr.code);
			}
			if(tmpArr.avgday>tmpArr.dayTL){//当前科室平均住院日超标
				seriesTL[1].data.push(tmpArr.code);
			}
			if(tmpArr.drugratio>tmpArr.drugTL){//当前科室药占比超标
				seriesTL[2].data.push(tmpArr.code);
			}
			//实际管理值
			if(tmpArr.avgfee>tmpArr.feeTT){//当前科室次均费用超标
				feeb_TT =true;
				seriesTT[0].data.push(tmpArr.code);
			}
			if(tmpArr.avgday>tmpArr.dayTT)
			{//当前科室平均住院日超标
				seriesTT[1].data.push(tmpArr.code);
			}
			if(tmpArr.drugratio>tmpArr.drugTT)
			{//当前科室药占比超标
				seriesTT[2].data.push(tmpArr.code);
			}
			//标杆管理值
			if(tmpArr.avgfee>tmpArr.feeB){//当前科室次均费用超标
				feeb_B = true;
				seriesB[0].data.push(tmpArr.code);
			}
			if(tmpArr.avgday>tmpArr.dayB){//当前科室平均住院日超标
				seriesB[1].data.push(tmpArr.code);
			}
			if(tmpArr.drugratio>tmpArr.drugB){//当前科室药占比超标
				seriesB[2].data.push(tmpArr.code);
			}
			if(feeb_B&&feeb_TT){
				tmpArr.attention=4;//关注度
			}
			else if(feeb_TT){
				tmpArr.attention=3;//关注度
			}
			else if(feeb_B){
				tmpArr.attention=2;//关注度
			}
			else {
				tmpArr.attention=1;//关注度
			}
			tableData.push(tmpArr);
		}
		
		//绘制venn图
		//年初管理值
		$('#vennchartsTargetLastYear'+tabId).jvenn({
			series:seriesTL,
			fnClickCallback : function() {
				// 绘制表格
				var category = "";
				for ( var i in this.listnames) {
					category += this.listnames[i]
							+ " ";
				}
				var depCodes = [];
				for ( var i in this.list) {
					depCodes.push(this.list[i]);
				}
				vennTable("TargetLastYear",depCodes, tableData,category);
			},
			exporting: false
		})
		//表格默认加载数据
		vennTable("TargetLastYear",seriesTL[0].data,tableData,"次均费用")
		//标杆管理值
		$('#vennchartsBenchmark'+tabId).jvenn({
			series : seriesB,
			fnClickCallback : function() {
				// 绘制表格
				var category = "";
				for ( var i in this.listnames) {
					category += this.listnames[i]
							+ " ";
				}
				var depCodes = [];
				for ( var i in this.list) {
					depCodes.push(this.list[i]);
				}
				vennTable("Benchmark",depCodes, tableData,category);
			},
			exporting: false
		})
		//表格默认加载数据
		vennTable("Benchmark",seriesB[0].data,tableData,"次均费用")
		//实际管理值
		$('#vennchartsTargetThisYear'+tabId).jvenn({
			series : seriesTT,
			fnClickCallback : function() {
				// 绘制表格
				var category = "";
				for ( var i in this.listnames) {
					category += this.listnames[i]
							+ " ";
				}
				var depCodes = [];
				for ( var i in this.list) {
					depCodes.push(this.list[i]);
				}
				vennTable("TargetThisYear",depCodes, tableData,category)
			},
			exporting: false
		})
		//表格默认加载数据
		vennTable("TargetThisYear",seriesTT[0].data,tableData,"次均费用")
	});
}
/**
 * 绘制venn图对应的表格
 * quotaCode 指标代码
 * code 科室代码
 * data 表格数据
 */
function vennTable(quotaCode,code,data,title){
	var selTL = "";
	var selB = "";
	var selTT = "";
	switch(quotaCode){
	case 'TargetLastYear':
		selTL = 'vennsel';
		break;
	case 'Benchmark':
		selB = "vennsel";
		break;
	case 'TargetThisYear':
		selTT = "vennsel";
		break;
	}
	var thead='<table id="depinfotable'+quotaCode+tabId+'" class="table table-striped" style="width:100%;">';
	thead+='<caption >'+title+'</caption>';
	thead+='<thead>';
	thead+='	<tr>';
	thead+='		<th> </th>';
	thead+='		<th>科室名称</th>';
	thead+='		<th>次均费用（元）</th>';
	thead+='		<th class = "'+selTL+'">年初管理值</th>';
	thead+='		<th class = "'+selB+'">标杆管理值</th>';
	thead+='		<th class = "'+selTT+'">实际管理值</th>';
	thead+='		<th>顺序</th>';
	thead+='		<th>关注度</th>';
	thead+='	</tr>';
	thead+='</thead>';
	thead+='<tbody></tbody></table>';
	$("#"+tabId+" #depQuotaMonitorTable"+quotaCode+tabId).html(thead);
	//数据过滤
	data = data.filter(function(item){
		if($.inArray(item.code, code)>-1)
		{return true}
	});
	
   var columns=[
                  {
                	  "data" : null,
                	  "defaultContent":'',
                	  "className" : 'details-control',
                	  "width" : '30px'
            	  },
                     { "data": "depname",
	                       "render": function(obj, type, full){
	                    	   return "<a title ='科室费用消耗指数'  href=\"javascript:depCostConsumptionIndex('"+full.code+"','"+full.name+"')\">"+ full.name + "</a>"
	                       }
	                     },
	                     { "data": "avgfee",
	                    	"type":"numeric-comma",
	                    	"render": function(obj, type, full){
	                    		if(full.avgfee==null)
                    			{
	                    			return "-";
                    			}
	                    		else
                    			{
                					return formatNumber((full.avgfee*1).toFixed(2));
                    			}
		                    }
	                    	 
	                     },
	                     { "data": "avgfee_TL",
	                    	 "type": "number-beforeHtml",
	                    	 "render": function(obj, type, full){
		                    		if(full.feeTL==null){
		                    			return "-";
	                    			}else{
                    					return formatNumber((full.feeTL*1).toFixed(2))+gridcompareValue(full.avgfee,full.feeTL);
	                    			}
			                    }
		                 },
	                     { "data": "avgfee_B",
		                	 "type": "number-beforeHtml",
		                	 "render": function(obj, type, full){
		                    		if(full.feeB==null){
		                    			return "-";
	                    			}
		                    		else{
		                    			return formatNumber((full.feeB*1).toFixed(2))+gridcompareValue(full.avgfee,full.feeB);
	                    			}
			                    } 
	                     },
	                     { "data": "avgfee_TT","type": "number-beforeHtml",
	                    	 "render": function(obj, type, full){
		                    		if(full.feeTT==null){
		                    			return "-";
	                    			}
		                    		else{
		                    			return formatNumber((full.feeTT*1).toFixed(2))+gridcompareValue(full.avgfee,full.feeTT);
	                    			}
			                    } 
	                     },
	                     { "data": "order","visible": false,
	                    	 "render": function(obj, type, full){
	                    		 return full.attention;
			                    } 
	                     },
	                     { "data": "attention",
	                    	 "render": function(obj, type, full){
	                    		 var str = "";
	                    		 for (var i=1 ;i<=full.attention;i++){
	                    			 str = str+"<span><font color='red'><i class='icon-star'></i></font></span>";
                    			 }
	                    		 str += "<span style='display:none'>"+full.attention+"</span>";
	                    		return str;
			                    } 
	                     }
	                 ];
	var paramsDataTables={info:false,order:[[ 6, "desc" ]],tableTitle:'未达标科室指标情况表',columnDefs:[{"orderable": false,"targets": [ 0,7 ] }]};
	paramsDataTables.scrollY='280px'; 
	paramsDataTables.bAutoWidth= false;
	var oaTable=$("#"+tabId+" #depinfotable"+quotaCode+tabId).dataTableBasic(columns,data,paramsDataTables);
	
	$("#"+tabId+" #depinfotable"+quotaCode+tabId).find("tbody").off("click", "td.details-control");
	$("#"+tabId+" #depinfotable"+quotaCode+tabId).find("tbody").on('click', 'td.details-control', function (){
		var nTr = $(this).closest('tr');
		var row = oaTable.row( nTr );
        var aData = row.data();
        if (row.child.isShown()) {//判断是否已打开
			row.child.hide();
			nTr.removeClass("shown");
		} else {
			nTr.addClass("shown");
			//获取要查询的关联指标的指标代码
			fnFormatDetails(row,aData);
		}
    
	});
	function fnFormatDetails(row,aData){
			row.child("正在加载...").show();
			try{
				var str = '';
				str+=' <table width="100%"  >  ';
				str+=' 	<thead>  ';
				str+=' 		<tr>  ';
				str+=' 			<td>指标名称</td>  ';
				str+=' 			<td>本期值</td>  ';
				str+=' 			<td>年初管理值</td>  ';
				str+=' 			<td>标杆管理值</td>  ';
				str+=' 			<td>实际管理值</td>  ';
				str+=' 		</tr>  ';
				str+=' 	</thead>  ';
				str+=' 	<tbody>  ';
				str += "	<tr>";
				str+=' 			<td>平均住院日</td>  ';
				str+=' 			<td>'+(aData.avgday==null?'-':(aData.avgday*1).toFixed(2))+'</td>';
				str+=' 			<td>'+(aData.dayTL==null?'-':(aData.dayTL*1).toFixed(2))+gridcompareValue(aData.avgday,aData.dayTL)+'</td>  ';
				str+=' 			<td>'+(aData.dayB==null?'-':(aData.dayB*1).toFixed(2))+gridcompareValue(aData.avgday,aData.dayB)+'</td>  ';
				str+=' 			<td>'+(aData.dayTT==null?'-':(aData.dayTT*1).toFixed(2))+gridcompareValue(aData.avgday,aData.dayTT)+'</td>  ';
				str += "	</tr>";
				str += "	<tr>";
				str+=' 			<td>药占比(%)</td>  ';
				str+=' 			<td>'+(aData.drugratio==null?'-':(aData.drugratio*1).toFixed(2))+'</td>  ';
				str+=' 			<td>'+(aData.drugTL==null?'-':(aData.drugTL*1).toFixed(2))+gridcompareValuePercent(aData.drugratio,aData.drugTL)+'</td>  ';
				str+=' 			<td>'+(aData.drugB==null?'-':(aData.drugB*1).toFixed(2))+gridcompareValuePercent(aData.drugratio,aData.drugB)+'</td>  ';
				str+=' 			<td>'+(aData.drugTT==null?'-':(aData.drugTT*1).toFixed(2))+gridcompareValuePercent(aData.drugratio,aData.drugTT)+'</td>  ';
				str += "	</tr>";
				str+=' 	</tbody>  ';
				str+=' </table>  ';
				row.child(str).show();
			}catch(e){
				row.child("出错了...").show();
			}
	}
}

/**
 * 
 * @ Discription:加载venn图
 * @Autor ：liuhongjun
 * @param totalQuota
 * @param divId
 * @param commonul
 * @returns
 * any
 * yibaoHomePage.js
 * 2017年7月20日下午8:27:08
 */
function loadVennDiv(totalQuota,divId,commonul) {			
	var str = '';
	var ul = '';
	for (var o in totalQuota) {
		var QuotaCode = totalQuota[o].data;	
		var quotas = QuotaCode[o];
		for (var o1 in quotas.data) {
			var quota = quotas.data[o1];
			var quotaCode = quota.quotaCode;
			var quotaName = quota.quotaName;
			if (o1 == 0) {
				ul += '       <li role="presentation" class="active"> ';
			} else {
				ul += '       <li role="presentation"> ';
			}
			ul += '           <a href="#' + quotaCode + '-tc' + tabId
					+ '" role="tab" data-toggle="tab">' + quotaName
					+ '</a> ';
			ul += '       </li> ';
			
		}
		ul +='<span class="to_right" title="指标解释" style="padding: 5px;font-size: 17px;color: #15BB6B;cursor: pointer;" id = "toShow"><i class="fa fa-tag" aria-hidden="true"></i></span>'
		$("#" + tabId +" #"+commonul).html(ul);
		// 开始拼接div
		if (o == 0) {
			str += '<div role="tabpanel" class="tab-pane active" id="'
					+ totalQuota[o].code + 'QuaId' + tabId + '">';
		} else {
			str += '<div role="tabpanel" class="tab-pane" id="'
					+ totalQuota[o].code + 'QuaId' + tabId + '">';
		}

		for (var o in QuotaCode) {
			var quotas = QuotaCode[o];
			str += ' <div class="paddingd10"> ';
			str += '   <div class="clearfix"></div> ';
			str += '   <div class="tab-content"> ';
			for (var o1 in quotas.data) {
				var quota = quotas.data[o1];
				var quotaCode = quota.quotaCode;
				var quotaName = quota.quotaName;
				var quotaDetil = quota.quotaDetil;
				if (o1 == 0) {
					str += '       <div role="tabpanel" class="tab-pane active" ' 
							        + '" quotaName="'+ quotaName+ '" quotaCode="'+ quotaCode+ '" id="'+ quotaCode+ '-tc'+ tabId+ '"> ';
				} else {
				str += '       <div role="tabpanel" class="tab-pane" quotaName="'+ quotaName+ '" quotaCode="'+ quotaCode+ '" id="'+ quotaCode+ '-tc'+ tabId+ '"> ';}
				str += '				<div class="showDetil"> <i class="fa fa-lightbulb-o fa-lg"></i> ';
				str +=					quotaName+' : '+quotaDetil;			
				str +='				</div>'	;
				str += '           <div class="row padding100"> ';
				str += '               <div class="col-xs-5"> ';
				str += '                   <div  id  = "venncharts'+quotaCode+tabId+'"></div>';
				str += '               </div> ';
				str += '               <div class="col-xs-7"> ';
				str += '               	<div id = "depQuotaMonitorTable'+quotaCode+tabId+'" style="white-space:nowrap">';//cb
				str += '               	</div> ';
				str += '               </div> ';
				str += '           </div> ';
				str += '       </div> ';
			}
			str += '   </div> ';
			str += ' </div> ';
		}
		str += '</div>';		
	}
	$("#" + tabId + " #" + divId).html(str);
}

/**
 * 
 * @ Discription:科室链
 * @Autor ：liuhongjun
 * @param depCode
 * @param depName
 * @returns
 * any
 * yibaoHomePage.js
 * 2017年6月22日下午8:45:26
 */
function depCostConsumptionIndex(depCode,depName){
	$.post(contextPath + "/yibaohome/getMaxDate.dhc").done(function(result) {
		if(result){
			var year=result.split('-');
			var dateFrom=year[0]+'-01-01';
			var dateTo=result;
			var param = jQuery.extend(true,{},paramTabPage[tabId]);
			param.pardepCode = depCode;
			param.pardepName = depName;
			param.dateFrom = dateFrom;
			param.dateTo = dateTo;
			openTab('/pages/yibao/home/costConsumptionIndex.jsp', depName+"|"+'费用消耗指数','costConsumptionIndex'+depCode, 'costConsumptionIndex'+depCode,param);
		}
	});
	
}